//
//  ViewController.m
//  KeyboardDidShow
//
//  Created by xisi on 13-12-5.
//  Copyright (c) 2013年 77. All rights reserved.
//

#import "XSKeyboardViewController.h"

@implementation XSKeyboardViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


#pragma mark -  view的处理
//_______________________________________________________________________________________________________________

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //  点击手势
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewEndEditing)];
    tapGestureRecognizer.numberOfTapsRequired = 2;          //  连续点击2次
    [self.view addGestureRecognizer:tapGestureRecognizer];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.view endEditing:YES];
    [self registerForKeyboardNotification];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}


/*!
    注册键盘显示、隐藏通知
 */
- (void)registerForKeyboardNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}


#pragma mark -  键盘的处理
//_______________________________________________________________________________________________________________

/*!
 处理键盘出现
 */
- (void)keyboardWillShow:(NSNotification *)notification {
    
    NSLog(@"显示键盘");
    NSDictionary *userInfo = [notification userInfo];
    NSTimeInterval duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue];
    
    UIWindow *window = [UIApplication sharedApplication].windows.firstObject;
    
    CGRect keyboardRect = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect viewRect = [_currentEditView.superview convertRect:_currentEditView.frame toView:window];
    
    CGFloat keyboardMinY = CGRectGetMinY(keyboardRect);
    CGFloat viewMaxY = CGRectGetMaxY(viewRect);
    
    CGFloat offsetY = keyboardMinY - viewMaxY - self.verticalGap;           //  负数表示要将self.view向上移动
    if (offsetY < 0) {          //  将要编辑的视图比较低
        NSLog(@"键盘--1");
        [self handleKeyboardToOffsetY:offsetY + self.view.transform.ty duration:duration options:curve];
    } else {
        NSLog(@"键盘--2");//  将要编辑的视图比较高
        if (self.view.transform.ty < 0) {               //  已经上移
            if (offsetY <= fabs(self.view.transform.ty)) {
                [self handleKeyboardToOffsetY:offsetY + self.view.transform.ty duration:duration options:curve];
            } else {
                [self handleKeyboardToOffsetY:0 duration:duration options:curve];
            }
        }
    }
    _lastShowNotification = notification;
}


/*!
 处理键盘隐藏
 */
- (void)keyboardWillHide:(NSNotification *)notification {
    NSLog(@"隐藏键盘");
    [self.view endEditing:YES];
    
//    NSDictionary *userInfo = [notification userInfo];
//    NSTimeInterval duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//    UIViewAnimationCurve curve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue];
//    [self handleKeyboardToOffsetY:0 duration:duration options:curve];
}


/*!
 将self.view上下移动
 */
- (void)handleKeyboardToOffsetY:(CGFloat)moveOffsetY duration:(NSTimeInterval)duration options:(UIViewAnimationCurve)curve {
    [UIView animateWithDuration:duration animations:^{
        [UIView setAnimationCurve:curve];
        self.view.transform = CGAffineTransformMakeTranslation(0, moveOffsetY);
    }];
}


/*!
 结束编辑，使键盘消失
 */
- (void)viewEndEditing {
    [self.view endEditing:YES];
}


#pragma mark -  下面2个方法需要使用super调用
//_______________________________________________________________________________________________________________

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [self changeCurrentEditView:textField];
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    [self changeCurrentEditView:textView];
    return YES;
}


/*!
    当切换正在编辑的是视图时，发出通知
 */
- (void)changeCurrentEditView:(UIView *)editView {
    if (_currentEditView == nil) {
        _currentEditView = editView;
    } else if (_currentEditView != editView) {
        _currentEditView = editView;
        [self keyboardWillShow:_lastShowNotification];
    }
}

@end
